package com.sc.admin.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sc.admin.common.ResponseResult;
import com.sc.admin.pojo.Role;
import com.sc.admin.pojo.User;
import com.sc.admin.pojo.UserRole;
import com.sc.admin.pojo.view.RoleView;
import com.sc.admin.service.RoleService;
import com.sc.admin.service.UserRoleService;
import com.sc.admin.service.UserService;

@Controller
@RequestMapping("/priv/user")
public class UserPrivController {
	@Autowired
	private UserRoleService urs;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@RequestMapping()
	public String showPage() {
		return "priv-user";
	}
	
	@RequestMapping("/list")
	public @ResponseBody Object userList(int page,int rows,User user) {
		int count = userService.getCount();
		List<User> users = userService.getUsers(page, rows,user);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("total", count);
		map.put("rows", users);
		return map;
	}
	
	@RequestMapping("/role/list")
	public @ResponseBody Object getUserRoles(int userId) {
		//返回符合easyui-datagrid前端要求的行集合
		List<RoleView> roleRows = new ArrayList<RoleView>();
		//权限
		List<UserRole> userRoles = urs.getUserRolesByUserId(userId);
		//角色
		List<Role> roles = roleService.getAllRoles();
		//选择权限
		for(Role role: roles) {
			RoleView row = new RoleView();
			row.setId(role.getId());
			row.setName(role.getName());
			for(UserRole ur : userRoles) {
				if(ur.getRoleId()==role.getId()) {
					row.setChecked(true);
					break;
				}
			}
			roleRows.add(row);
		}
		
		return roleRows;
	}

	@RequestMapping(value="/role/add",method=RequestMethod.POST)
	public @ResponseBody Object addUserRoles(int userId,String ids) {
		urs.addUserRole(userId, ids);
		return new ResponseResult().ok();
	}

}
